/**
 * Copyright ©2012-2018 HopeHaiyang Corporation, All Rights Reserved
 * http://www.wuhanhope.com
 */
package hujia.profile.server.img;

import hujia.profile.domain.Role;
import hujia.profile.server.header.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * class info
 *
 * @author hujia
 *         Create at 2018/7/31 9:28
 */
@Service
public class UserDetailsServiceImg implements UserDetailsService {

    @Autowired
    private UserService service;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        Optional<hujia.profile.domain.User> user = service.getByUserName(userName);
        if (!user.isPresent()) {
            throw new UsernameNotFoundException(userName);
        }
        Role role = user.get().getRole();
        List<SimpleGrantedAuthority> grantedAuthority = new ArrayList<SimpleGrantedAuthority>();
        grantedAuthority.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        User springUser = new User(user.get().getUserName(), user.get().getPassword(), true, true, true, true, grantedAuthority);
        return springUser;
    }
}
